import { List, WhiteSpace, Button, WingBlank, Toast } from 'antd-mobile';
import { Component } from 'react'
import StandardForm from '@/components/standardForm'
import router from 'umi/router';
import { trim } from '@/utils'
import { connect } from 'dva'
@connect(({ manager, loading }) => {
  return {
    manager,
  }
})
class Update extends Component {
  constructor(props) {
    super(props)
    this.submit = this.submit.bind(this)
  }
  instantForm = null
  componentWillMount() {
    this.getWorkerInfo()
  }
  submit() {
    const { dispatch, location: {query} } = this.props
    this.instantForm.validateFields((err, values)=> {
      if(err) return
      values.wages = +values.wages
      const payload = {
        ...values,
        wages: +values.wages,
        phone: trim(values.phone),
        userId: query.id
      }
      dispatch({
        type: 'manager/updateWorker',
        payload: payload
      }).then(res => {
        Toast.success(res.msg)
        setTimeout(() => {
          router.go(-1)
        }, 1000)
      }).catch(err => {
        Toast.fail('更新失败')
      })
    })

  }
  getWorkerInfo() {
    const { dispatch, location: {query} } = this.props
    dispatch({
      type: 'manager/getWorkerInfo',
      payload: {
        id: query.id
      }
    })
  }
  renderForm() {
    const { manager: {workerInfo={}} } = this.props
    const formItems = [
      {
        name: 'name',
        label: '姓名',
        placeholder: "请输入员工姓名",
        options: {
          initialValue: workerInfo.name,
          rules: [{required: true}]
        }
      },
      {
        name: 'phone',
        label: '手机',
        placeholder: "请输入员工手机",
        layoutOption: {
          maxLength: 11
        },
        options: {
          initialValue: workerInfo.phone,
          rules: [
            {required: true },
            {pattern: /^\d{11}$/ }
          ]
        }
      },
      {
        name: 'wages',
        label: '工资(天)',
        placeholder: "请输入员工工资",
        layoutOption: {
          extra: '元',
          type: 'money',
          moneyKeyboardAlign: 'left',
        },
        options: {
          initialValue: workerInfo.wages,
          rules: [{required: true}]
        }
      }
    ]
    return <StandardForm
      wrappedComponentRef={el => this.instantForm = el}
      formItems={formItems}
    />
  }
  render() {
    return (
      <WingBlank style={{paddingTop: '200px'}} >
        <List>
          {this.renderForm()}
        </List>
        <WhiteSpace />
        <Button type="primary" onClick={this.submit}>提交</Button>
      </WingBlank>
    )
  }
}
export default Update